#ifndef __GETWEATHER_HPP__
#define __GETWEATHER_HPP__

#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QString>
#include <QObject>
#include <QUrl>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QUrlQuery>
#include <QCoreApplication>
#include <QTimer>
#include <QJsonParseError>

#include <iostream>
#include <string>
#include <sstream>

#include <locale>       // 添加 locale 支持
#ifdef _WIN32
#include <windows.h>    // Windows 系统需要
#endif

//#include "./CjsonObject/CJsonObject.hpp"

#define API_KEY "SAewqnjWlC7dvMLfL"

// 定义一个结构体来存储结果
struct WeatherResult {
    bool success;
    std::string message;
};

struct WeatherInfo
{
    QString temperature;
    QString condition;
    QString humidity;
    QString windDirection;
    QString windSpeed;
    QString updateTime;
};

class GetWeather : public QObject
{
    Q_OBJECT

public:
    explicit GetWeather(QObject *parent = nullptr);
    ~GetWeather();

    // 新的便捷方法
    void fetchWeatherByCity(const QString &apiKey, const QString &city);
    void fetchWeatherData(const QString &url);

    // 添加新的公共方法用于获取最后一次的天气数据
    QString getLastTemperature() const { return lastWeatherInfo.temperature; }
    QString getLastCondition() const { return lastWeatherInfo.condition; }
    QString getLastHumidity() const { return lastWeatherInfo.humidity; }
    QString getLastWindDirection() const { return lastWeatherInfo.windDirection; }
    QString getLastWindSpeed() const { return lastWeatherInfo.windSpeed; }
    QString getLastUpdateTime() const { return lastWeatherInfo.updateTime; }

    // 获取格式化的天气信息字符串
    QString getFormattedWeatherInfo() const;

signals:
    // 保持原有信号用于兼容性
    void weatherDataFetched(const QString &data);
    void errorOccurred(const QString &error);

    // 新增结构化数据信号
    void weatherInfoReceived(const WeatherInfo &info);

private slots:
    void onFinished(QNetworkReply *reply);

private:
    QNetworkAccessManager *manager;
    WeatherInfo parseWeatherData(const QByteArray &data);
    bool validateApiKey(const QString &apiKey);
    bool validateCity(const QString &city);

    WeatherInfo lastWeatherInfo; // 存储最后一次获取的天气信息
    void updateLastWeatherInfo(const WeatherInfo &info);
};

std::string getWeatherString(const std::string& city);
void extractWeatherAndTemperature(const std::string& weatherInfo, std::string& outTemp, std::string& outWeather);
std::string translateChineseWeather(const std::string &chineseWeather);
void initConsole();

#endif // GETWEATHER_HPP
